export default {
	// 为当前模块开启命名空间
	namespaced: true,
	// 模块的 state 数据
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart')  || '[]')
	}),
	// 模块的 mutations 方法
	mutations: {
		addToCart(state, goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}
			if(goods.sum){
				findResult.goods_count = goods.goods_sum
			}
			console.log(state.cart);
			this.commit('m_cart/saveStoryage')
		},
		// 更新购物车当前商品选中状态
		updataGoodsState(state, goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveStoryage')
			}
		},
		// 删除商品
		deleteCartGoods(state, goods){
			console.log(state.cart);
			state.cart = state.cart.filter(item => item.goods_id !== goods)
			console.log(state.cart);
			this.commit('m_cart/saveStoryage')
		},
		// 全选商品
		goodsTotalChecked(state, val){
			state.cart.forEach(i => {
				i.goods_state = val
			})
			this.commit('m_cart/saveStoryage')
		},
		saveStoryage(state){
			console.log('开始存储');
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		// 购物车商品总数
		total(state){
			let num = 0
			state.cart.forEach( (i) => {
				num += i.goods_count
			})
			return num
		},
		// 选中的总数
		checkCount(state){
			const obj = state.cart.filter(item => item.goods_state === true)
			// console.log(obj);
			return obj
		}
	},
}